﻿using System.Linq;
using System.Web.Mvc;
using Century.Web.Security.Attributes;
//using Century.Models.Common;
//using Century.Common.Business.BOL.Common;
using Century.Web.UI.MVC;
//using Century.Models.ViewModels;
//using Century.Business.Repository;
using System.Collections.Generic;
//using Century.Common.Config;
//using Century.Globalization;
//using Century.Common.Enumerations;
using System;
using System.Web;
using System.IO;
using Century.Model.CMS;
using Century.Business.CMS;

namespace Century.Admin.Controllers
{
    //[Authorization(Group = "", Name = "SiteManager")]
    public class SiteManagementController : CenturyAdminBaseController
    {
        public SiteManagementController(ISiteService siteService) : base(siteService) { }

        public string CurrentAnalysisDate { 
            get 
            {
                if (Session["CurrentAnalysisDate"] == null)
                {
                    Session["CurrentAnalysisDate"] = string.Empty;
                }
                return Session["CurrentAnalysisDate"].ToString();
            } 
            set 
            { 
                Session["CurrentAnalysisDate"] = value; 
            } 
       }
        public ActionResult Index()
        {
            return View();
        }

        #region Site Social Links

        public ActionResult SocialNetworks()
        {
            return View();
        }

        [HttpPost]
        public void SaveSocialNetworks(FormCollection elements)
        {
            Dictionary<string, string> links = new Dictionary<string, string>();

            //links.Add(SiteConfigKey.FacebookLink.ToString(), elements[SiteConfigKey.FacebookLink.ToString()]);
            //links.Add(SiteConfigKey.TwitterLink.ToString(), elements[SiteConfigKey.TwitterLink.ToString()]);
            //links.Add(SiteConfigKey.YoutubeLink.ToString(), elements[SiteConfigKey.YoutubeLink.ToString()]);
            //links.Add(SiteConfigKey.LinkedInLink.ToString(), elements[SiteConfigKey.LinkedInLink.ToString()]);
            //links.Add(SiteConfigKey.RssFeedLink.ToString(), elements[SiteConfigKey.RssFeedLink.ToString()]);
            //links.Add(SiteConfigKey.VimeoLink.ToString(), elements[SiteConfigKey.VimeoLink.ToString()]);
            //links.Add(SiteConfigKey.GooglePlusLink.ToString(), elements[SiteConfigKey.GooglePlusLink.ToString()]);

            //SiteConfigReader.Instance.SaveSocialNetworkLink(links);
            //SiteConfigReader.Instance.Reload();
        }

        #endregion

        #region Site Configs

        public ActionResult SiteConfigs()
        {
            //using (CountrySiteEmailBSO csBSO = new CountrySiteEmailBSO())
            //{
            //    foreach (Century.Common.Enumerations.EmailConfigType type in Enum.GetValues(typeof(Century.Common.Enumerations.EmailConfigType)))
            //    {
            //        TempData[type.ToString()] = csBSO.GetEmailConfig(type, PersistData.CurrentSiteId);
            //    }
            //}
            return View();
        }

        [HttpPost]
        public ActionResult SiteConfigs(FormCollection elements)
        {
            // contact phone
            //string contactPhone = elements[SiteConfigKey.ContactPhone.ToString()];
            //SiteConfigReader.Instance.SaveConfig(SiteConfigKey.ContactPhone, contactPhone);
            //SiteConfigReader.Instance.Reload();

            //// save country site emails
            //using (CountrySiteEmailBSO csBSO = new CountrySiteEmailBSO())
            //{
            //    foreach (Century.Common.Enumerations.EmailConfigType type in Enum.GetValues(typeof(Century.Common.Enumerations.EmailConfigType)))
            //    {
            //        csBSO.SaveEmailConfig(type, elements[type.ToString()], PersistData.CurrentSiteId);
            //    }
            //}

            return View();
        }

        #endregion

        #region Site Daily Analysis

        private void FillDailyAnalysisParts()
        {
            //var enumValues = Enum.GetValues(typeof(DailyAnalysisPotentialDirections)).Cast<DailyAnalysisPotentialDirections>().Select(e => new KeyValuePair<int, string>((int)e, e.ToString()));
            //ViewBag.PotentialDirection = new SelectList(enumValues, "Key", "Value");
            //using (DailyAnalysisBSO bso = new DailyAnalysisBSO())
            //{

            //    //string now = DateTime.Now.ToShortDateString();
            //    int day = DateTime.Now.Day;
            //    int month = DateTime.Now.Month;
            //    int year = DateTime.Now.Year;

            //    if (!string.IsNullOrEmpty(CurrentAnalysisDate))
            //    {
            //        day = int.Parse(CurrentAnalysisDate.Substring(0, 2));
            //        month = int.Parse(CurrentAnalysisDate.Substring(2, 2));
            //        year = int.Parse(CurrentAnalysisDate.Substring(4, 4)); // 26 08 2001
            //        //daList = daList.Where(d => d.AnalysisDate.Day == day && d.AnalysisDate.Month == month && d.AnalysisDate.Year == year).OrderBy(d => d.Order).ToList();
            //    }

            //    List<DailyAnalysis> daList = bso.GetList(d =>
            //                                                d.CountrySiteId == PersistData.CurrentSiteId &&
            //                                                d.AnalysisDate.Month == month &&
            //                                                d.AnalysisDate.Day == day &&
            //                                                d.AnalysisDate.Year == year).OrderBy(d => d.Order).ToList();

                
            //    ViewBag.DailyAnalysisList = daList;

            //    string dateStr = DateTime.Now.Day.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Year.ToString();

            //    List<string> olders = bso.GetList(d => d.CountrySiteId == PersistData.CurrentSiteId &&
            //                                           d.AnalysisDate < DateTime.Today
            //                                     )
            //                             .Select(d => (d.AnalysisDate.Day.ToString("D2") + "." + d.AnalysisDate.Month.ToString("D2") + "." + d.AnalysisDate.Year.ToString()))
            //                             .Distinct()
            //                             .ToList();

            //    ViewBag.OlderDailyAnalysisTimes = olders;
            //}
        }

        public ActionResult DailyAnalysis()
        {
            FillDailyAnalysisParts();
            return View();
        }

        /* with old analysis date */
        public void SetCurrentDailyAnalysisDate(string id)
        {
            CurrentAnalysisDate = id;
            FillDailyAnalysisParts();
        }

        //[HttpPost]
        //public ActionResult DailyAnalysis(DailyAnalysis model)
        //{
        //    using (DailyAnalysisBSO daBSO = new DailyAnalysisBSO())
        //    {
        //        if (model.Id == 0)
        //        {
        //            DailyAnalysis lastItem = daBSO.GetList(d => d.CountrySiteId == PersistData.CurrentSiteId &&
        //                                            d.AnalysisDate.Month == DateTime.Now.Month &&
        //                                            d.AnalysisDate.Day == DateTime.Now.Day &&
        //                                            d.AnalysisDate.Year == DateTime.Now.Year).FirstOrDefault();
        //            int maxOrder = lastItem != null ? lastItem.Order : 0;

        //            model.CountrySiteId = PersistData.CurrentSiteId;
        //            model.Order = maxOrder + 1;
        //            model.AnalysisDate = DateTime.Now;
                    
        //            daBSO.Insert(model);
        //        }
        //        else
        //        {
        //            DailyAnalysis entity = daBSO.GetById(model.Id);
        //            entity.AlternativeScenario = model.AlternativeScenario;
        //            entity.ExpiryTime = model.ExpiryTime;
        //            entity.KeyLevel = model.KeyLevel;
        //            entity.Note = model.Note;
        //            entity.PotentialDirection = model.PotentialDirection;
        //            entity.Product = model.Product;
        //            entity.Resistance = model.Resistance;
        //            entity.SupportVal = model.SupportVal;
        //            entity.Target = model.Target;
        //            entity.DailyReview = Server.HtmlDecode(model.DailyReview);
        //            daBSO.Update(entity);
        //        }
        //    }
        //    FillDailyAnalysisParts();
        //    return View(model);
        //}

        //public JsonResult DailyAnalysisEdit(string id)
        //{
        //    using (DailyAnalysisBSO daBSO = new DailyAnalysisBSO())
        //    {
        //        return Json(daBSO.GetById(Convert.ToInt32(id)));
        //    }
        //}

        public void DailyAnalysisDelete(string id)
        {
            //using (DailyAnalysisBSO daBSO = new DailyAnalysisBSO())
            //{
            //    DailyAnalysis entry = daBSO.GetById(Convert.ToInt32(id));
            //    daBSO.Delete(entry);
            //}
            FillDailyAnalysisParts();
        }

        public ActionResult DailyAnalysisList()
        {
            FillDailyAnalysisParts();
            return View();
        }

        public ActionResult DailyAnalysisFileUpload(IEnumerable<HttpPostedFileBase> attachments)
        {
            //// The Name of the Upload component is "attachments" 
            //foreach (var file in attachments)
            //{
            //    // Some browsers send file names with full path. This needs to be stripped.
            //    var fileName = string.Format("{0}_{1}", DateTime.Now.ToShortDateString().Replace(".", string.Empty), Path.GetFileName(file.FileName));
            //    var physicalPath = Path.Combine(Server.MapPath(ConfManager.Instance.Common.DailyAnalysisImagesPath.ConfigValue), PersistData.CurrentSite.Path, fileName);
            //    string onlyPath = Path.Combine(Server.MapPath(ConfManager.Instance.Common.DailyAnalysisImagesPath.ConfigValue), PersistData.CurrentSite.Path);
            //    if (!System.IO.Directory.Exists(onlyPath))
            //    {
            //        System.IO.Directory.CreateDirectory(onlyPath);
            //    }
            //    // The files are not actually saved in this demo
            //    file.SaveAs(physicalPath);
            //}
            //// Return an empty string to signify success
            return Content("");
        }

        public ActionResult DailyAnalysisFileRemove(string[] fileNames)
        {
            //// The parameter of the Remove action must be called "fileNames"
            //foreach (var fullName in fileNames)
            //{
            //    var fileName = Path.GetFileName(fullName);
            //    var physicalPath = Path.Combine(Server.MapPath(ConfManager.Instance.Common.DailyAnalysisImagesPath.ConfigValue), PersistData.CurrentSite.Path, fileName);

            //    if (System.IO.File.Exists(physicalPath))
            //    {
            //        // The files are not actually removed in this demo
            //        System.IO.File.Delete(physicalPath);
            //    }
            //}
            //// Return an empty string to signify success
            return Content("");
        }

        #endregion

        protected SitePage GetSitePage(int? pageID)
        {
           return siteService.GetPage(pageID ?? 0);
            //using (SitePageBSO sp = new SitePageBSO())
            //{
            //    return sp.GetById(pageID.HasValue ? pageID.Value : 0);
            //}
        }

        #region Page Context Menu Actions

        public ActionResult AddNewSubPage(int? id)
        {
            return View(GetSitePage(id ?? 0));
        }

        public ActionResult CopyPageAs(int? id)
        {
            return View(GetSitePage(id ?? 0));
        }

        public ActionResult DisableOrEnablePage(int? id)
        {
            return View(GetSitePage(id ?? 0));
        }

        #endregion

        #region Site Context Menu Actions

        public ActionResult AddNewPage(int? id)
        {
            return View();
        }

        public ActionResult CopySiteAs(int? id)
        {
            //using (SitePageBSO sp = new SitePageBSO())
            //{
            //    PageDetail pageDetail = new PageDetail();
            //    pageDetail.Page = sp.GetAll().Where(p => p.Id == (id.HasValue ? id.Value : 0)).FirstOrDefault();
            //    return View(pageDetail);
            //}
            return View();
        }

        public ActionResult DisableOrEnableSite(int? id)
        {
            //using (SitePageBSO sp = new SitePageBSO())
            //{
            //    PageDetail pageDetail = new PageDetail();
            //    pageDetail.Page = sp.GetAll().Where(p => p.Id == (id.HasValue ? id.Value : 0)).FirstOrDefault();
            //    return View(pageDetail);

            //}

            return View();
        }

        #endregion

        #region Application Detail

        public ActionResult ApplicationDetails(string id)
        {
            return View("ApplicationDetails", model: id);
        }

        #endregion
    }
}
